﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;
using System.Configuration;
using System.IO;

namespace Catering.UserTraining.SlrClassTraining
{
    public partial class classtraining_books_add : UserIsNull
    {
        public int m_LessonID = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            m_LessonID = CommRequest.GetInt("LessonID", 0);
            if (!IsPostBack)
            {
                //增加或者修改判断。
                if (!string.IsNullOrEmpty(CommRequest.GetString("Flag")))
                {
                    this.hid_Flag.Value = CommRequest.GetString("Flag");
                }

                if (this.hid_Flag.Value == "EDIT")
                {
                    this.InitBooksInfo(CommRequest.GetInt("BookID", 0));
                }

                this.InitBasePageInfo();
            }
        }

        public void InitBasePageInfo()
        {
            List<Catering_Model.BookType> _listBookType = new Catering_Rules.BookType().GetModelList(" Status='O'AND BookClass='5' ");
            this.ddlBookTypeID.DataSource = _listBookType;
            this.ddlBookTypeID.DataTextField = "BookTypeName";
            this.ddlBookTypeID.DataValueField = "BookTypeID";
            this.ddlBookTypeID.DataBind();
        }

        public void InitBooksInfo(int BookID)
        {
            Catering_Model.ClassBooks _BooksModel = new Catering_Model.ClassBooks();
            _BooksModel = new Catering_Rules.ClassBooks().GetModel(BookID);
            if (_BooksModel == null) return;
            ViewState["EditBooksModel"] = _BooksModel;
            this.txt_BookNo.Text = _BooksModel.BookNo;
            this.ddlBookTypeID.SelectedValue = _BooksModel.BookTypeID.ToString();
            this.txt_LearnTime.Text = _BooksModel.LearnTime.ToString();
            this.txt_Remarks.Text = _BooksModel.Remarks;
            //this.txt_PagesCount.Text = _BooksModel.PagesCount.ToString();
            this.chk_IsShare.Checked = _BooksModel.IsShare;
            //this.txt_BookAuthorName.Text = _BooksModel.BookAuthorName;
            string LastBooksAddr = ConfigurationManager.AppSettings["FileRoot"] + "SlrClassbooks/" + _BooksModel.BookAddr;
            this.UploadList.InnerHtml = "<dl><dd><a href='" + LastBooksAddr + "'>" + _BooksModel.BookName + "</a></dd></dl>";
        }

        /// <summary>
        /// 添加或者修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //1.获取上传文件
            string sFiles = this.hf_UploadFile.Value;
            string sMsg = ""; //错误提示
            string sTempAddre = "";
            Catering_Model.ClassBooks _BooksModel = new Catering_Model.ClassBooks();
            _BooksModel.BookNo = this.txt_BookNo.Text.Trim();
            _BooksModel.BookTypeID = int.Parse(this.ddlBookTypeID.SelectedValue);
            _BooksModel.IsShare = true;
            //_BooksModel.BookAuthorName = this.txt_BookAuthorName.Text.Trim();
            _BooksModel.BookAuthorName = "admin";
            _BooksModel.LearnTime = int.Parse(this.txt_LearnTime.Text.Trim());
            _BooksModel.Remarks = this.txt_Remarks.Text.Trim();
            _BooksModel.Status = this.ddlStatus.SelectedValue;
            //_BooksModel.PagesCount = int.Parse(this.txt_PagesCount.Text.Trim());
            _BooksModel.PagesCount = 1;
            _BooksModel.IsSplitPages = false;
            if (this.hid_Flag.Value == "EDIT")
            {
                Catering_Model.ClassBooks _OldBooksModel = (Catering_Model.ClassBooks)ViewState["EditBooksModel"];
                _BooksModel.BookID = _OldBooksModel.BookID;
                _BooksModel.BookAuthorID = _OldBooksModel.BookAuthorID;
                _BooksModel.UpUserName = _OldBooksModel.UpUserName;
                _BooksModel.UpUserID = _OldBooksModel.UpUserID;
                _BooksModel.UpDateTime = _OldBooksModel.UpDateTime;
                _BooksModel.CreateDate = _OldBooksModel.CreateDate;
                _BooksModel.BookName = _OldBooksModel.BookName;
                _BooksModel.BookSize = _OldBooksModel.BookSize;
                _BooksModel.BookSuff = _OldBooksModel.BookSuff;
                _BooksModel.FileType = _OldBooksModel.FileType;
                _BooksModel.BookAddr = _OldBooksModel.BookAddr;
                if (!string.IsNullOrEmpty(sFiles))
                {
                    string[] sObjList = sFiles.TrimEnd('┃').Split('┃');
                    string[] sObj = sObjList[0].TrimEnd(',').Split(',');
                    if (sObj.Length == 3)
                    {
                        string sFullFileName = CommUtils.UrlDecode(sObj[0]);//文档名称（包括后缀）
                        string sFileSize = sObj[1]; //文档大小
                        string sAddress = sObj[2]; //文档地址
                        string sType = ""; //文档类型
                        string sSuff = ""; //文档后缀
                        string sName = ""; //文档名称
                        CommUtils.GetFileInfo(sFullFileName, out sName, out sType, out sSuff);
                        _BooksModel.BookName = sFullFileName;
                        _BooksModel.BookSize = int.Parse(sFileSize);
                        _BooksModel.BookSuff = sSuff;
                        _BooksModel.FileType = sType;
                        _BooksModel.BookAddr = sAddress;
                        sTempAddre = sObj[2];
                    }
                }
                new Catering_Rules.ClassBooks().CheckBookModel(_BooksModel, out sMsg);
                if (string.IsNullOrEmpty(sMsg) && new Catering_Rules.ClassBooks().Update(_BooksModel))
                {
                    //保存成功后将文件移到SlrPubbooks中
                    if (!string.IsNullOrEmpty(sTempAddre))
                    {
                        MoveFile(sTempAddre, _BooksModel.BookAddr);
                        CommUtils.DeleteFile(ConfigurationManager.AppSettings["FileRoot"] + "SlrClassbooks/" + _OldBooksModel.BookAddr, true);
                        FileConvert_SWF.ConvertPdfToSwf(ConfigurationManager.AppSettings["FileRoot"] + "SlrClassbooks/" + _BooksModel.BookAddr);
                    }
                    RegisterStartupScript("保存成功!");
                }
                else
                {
                    RegisterStartupScript("保存失败！");
                }
            }
            else
            {
                if (string.IsNullOrEmpty(sFiles))
                {
                    RegisterStartupScript("请选择需要上载的文件！");
                    return;
                }
                string[] sObjList = sFiles.TrimEnd('┃').Split('┃');
                string[] sObj = sObjList[0].TrimEnd(',').Split(',');
                if (sObj.Length == 3)
                {
                    string sFullFileName = CommUtils.UrlDecode(sObj[0]);//文档名称（包括后缀）
                    string sFileSize = sObj[1]; //文档大小
                    string sAddress = sObj[2]; //文档地址
                    string sType = ""; //文档类型
                    string sSuff = ""; //文档后缀
                    string sName = ""; //文档名称                    
                    CommUtils.GetFileInfo(sFullFileName, out sName, out sType, out sSuff);
                    _BooksModel.BookName = sFullFileName;
                    _BooksModel.BookAuthorID = 0;
                    _BooksModel.UpUserName = Session["User"].ToString();
                    _BooksModel.UpUserID = int.Parse(Session["UserID"].ToString());
                    _BooksModel.BookSize = int.Parse(sFileSize);
                    _BooksModel.UpDateTime = DateTime.Now;
                    _BooksModel.CreateDate = DateTime.Now;
                    _BooksModel.BookSuff = sSuff;
                    _BooksModel.FileType = sType;
                    _BooksModel.BookAddr = sAddress;
                    new Catering_Rules.ClassBooks().CheckBookModel(_BooksModel, out sMsg);

                    if (string.IsNullOrEmpty(sMsg))
                    {
                        int intNewBookID = new Catering_Rules.ClassBooks().Add(_BooksModel);
                        if (intNewBookID > 0)
                        {
                            //保存成功后将文件移到SlrPubbooks中
                            MoveFile(sObj[2], sAddress);
                            FileConvert_SWF.ConvertPdfToSwf(ConfigurationManager.AppSettings["FileRoot"] + "SlrClassbooks/" + _BooksModel.BookAddr);
                            AddClassLessonsBooks(intNewBookID);
                            RegisterStartupScript("保存成功!");

                        }
                        else
                        {
                            RegisterStartupScript("保存失败！");
                        }
                    }
                    else
                    {
                        RegisterStartupScript("保存失败！");
                    }
                }
                else
                {
                    RegisterStartupScript("保存失败！");
                }
            }
        }

        public void AddClassLessonsBooks(int intNewBookID)
        {
            Catering_Model.ClassLessonsBooks _LessonsModel = new Catering_Model.ClassLessonsBooks();
            _LessonsModel.LessonID = m_LessonID;
            _LessonsModel.BookID = intNewBookID;
            _LessonsModel.AddUserID = int.Parse(Session["UserID"].ToString());
            _LessonsModel.AddDate = DateTime.Now;
            new Catering_Rules.ClassLessonsBooks().Add(_LessonsModel);
        }

        public void RegisterStartupScript(string strMessage)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Affect", "alert('" + strMessage + "！')", true);
        }

        private void MoveFile(string sFileName, string sNewFileName)
        {
            string oldpath = ConfigurationManager.AppSettings["FileRoot"] + "TempUpFile/";
            string newpath = ConfigurationManager.AppSettings["FileRoot"] + "SlrClassbooks/";
            string filedir = Path.GetDirectoryName(sNewFileName);      //文件目录
            if (CommUtils.FileExists(oldpath + sFileName, true))
            {
                CommUtils.FileMove(oldpath + sFileName, newpath + sNewFileName, newpath + filedir + "/", true);
            }
        }

        protected void btn_Return_Click(object sender, EventArgs e)
        {
            string url = "~/UserTraining/SlrClassTraining/classtraining_books_list.aspx?LessonID=" + m_LessonID;
            Response.Redirect(url);
        }
    }
}